package com.jd.platform.gobrs.client.handler.auto;

import com.jd.platform.gobrs.client.callback.ValueModel;
import com.jd.platform.gobrs.client.core.key.IKeyOwner;
import com.jd.platform.gobrs.client.core.key.auto.AutoKeyBuilder;
import com.jd.platform.gobrs.client.core.key.KeyHandlerFactory;
import com.jd.platform.gobrs.client.core.key.KeyHotModel;
import com.jd.platform.gobrs.client.handler.AbstractAutoCacheHandler;
import com.jd.platform.gobrs.common.enums.CacheHandlerEnums;
import com.jd.platform.gobrs.common.model.typeenum.KeyType;
import com.jd.platform.gobrs.common.tool.Constant;

/**
 * @program: gobrs
 * @ClassName AutoCache
 * @description:
 * @author: sizegang
 * @create: 2022-01-08 15:25
 * @Version 1.0
 **/
public class AutoCache extends AbstractAutoCacheHandler {

    private AutoKeyBuilder autoKeyBuilder = IKeyOwner.getAutoKeyBuilder();

    @Override
    public Integer getType() {
        return CacheHandlerEnums.AUTO_CACHE.getType();
    }

    @Override
    public boolean isHotKey(String key) {
        return false;
    }

    @Override
    public void remove(String key) {

    }

    @Override
    public Object doGetCache(String key, KeyType keyType) {
        Object userValue = null;
        ValueModel value = getValueSimple(key);
        if (value == null) {
            autoKeyBuilder.buildPrepareSend(key, keyType);
        } else {
            //临近过期了，也发
            if (isNearExpire(value)) {
                autoKeyBuilder.buildPrepareSend(key, keyType);
            }
            Object object = value.getValue();
            //如果是默认值，也返回null
            if (object instanceof Integer && Constant.MAGIC_NUMBER == (int) object) {
                userValue = null;
            } else {
                userValue = object;
            }
        }
        //统计计数
        KeyHandlerFactory.getCounter().collect(new KeyHotModel(key, value != null));
        return userValue;
    }

}
